<template>
  <a-drawer title="新增图标" :width="300" :visible="visible" :body-style="{ paddingBottom: '80px' }" @close="closeDrawer">
    <!-- 上传图标 -->
    <div style="margin: 0 70px">
      <a-upload v-model:file-list="fileList" list-type="picture-card" class="avatar-uploader" :before-upload="beforeUpload" :remove="handleRemove">
        <div v-if="fileList.length < 1">
          <plus-outlined></plus-outlined>
        </div>
      </a-upload>
    </div>
    <a-popconfirm title="你确定要上传这张图片？" ok-text="是的" cancel-text="不是" @confirm="handleUpload" :disabled="fileList.length > 0 ? false : true">
      <a-button type="primary" ghost :loading="uploading" style="margin-top: 16px" block>上传 </a-button>
    </a-popconfirm>
    <!-- 图标列表 -->
    <p style="text-align: center; color: #999; padding: 20px" v-show="isNull">没有图标，请上传</p>
    <div v-show="!isNull" class="iconList">
      <p class="iconList__title">已上传图标列表</p>
      <p class="iconList__text">请选择一张</p>
      <div class="iconList__items">
        <span v-for="(item, index) in iconList" :key="index" class="iconList__items__item">
          <img :src="item.url" :class="{ icon_border: index == current }" @click="chooseImg(item, index)" />
        </span>
      </div>
    </div>
    <!-- 按钮 -->
    <a-row type="flex" justify="end" v-show="!isNull">
      <a-space size="middle">
        <a-button type="primary" danger @click="removeIcon">删除该图标</a-button>
        <a-button type="primary" @click="chooseIcon">选择该图标</a-button>
      </a-space>
    </a-row>
  </a-drawer>
</template>

<script lang="ts">
import { PlusOutlined } from '@ant-design/icons-vue'
import { defineComponent, ref, toRaw, Ref, onUpdated } from 'vue'
import { message } from 'ant-design-vue'
import { upload, get, detele } from '../../utils/request/request'

interface FileItem {
  uid: string
  name?: string
  status?: string
  response?: string
  url?: string
  type?: string
  size: number
  originFileObj: any
}

interface IconList {
  url: string
  path: string
}
// 图标列表数据
const iconList: Ref<IconList[]> = ref([])

// drawer相关逻辑
const useDrawerEffect = (emit: any, chosImg: Ref<IconList>, isNull: Ref<boolean>) => {
  const visible = ref<boolean>(false)
  const { deleteIcon } = useHttpRequestEffect()
  const showDrawer = () => {
    visible.value = true
  }
  const closeDrawer = () => {
    visible.value = false
  }
  const chooseIcon = () => {
    emit('chosIcon', chosImg)
    visible.value = false
  }
  const removeIcon = () => {
    const path = chosImg.value.path
    const icon_name: string = path.split('assets/icons/recruitment/')[1]
    deleteIcon(icon_name).then(() => {
      if (iconList.value.length == 1) {
        iconList.value = []
        isNull.value = true
      } else {
        let index = iconList.value.findIndex((icon: IconList) => {
          return (icon.path = path)
        })
        iconList.value.splice(index + 1, 1)
      }
    })
  }
  return { visible, showDrawer, closeDrawer, chooseIcon, removeIcon }
}

// 上传图片相关逻辑
const useUploadEffect = (isNull: Ref<boolean>) => {
  const fileList = ref<FileItem[]>([])
  const uploading = ref<boolean>(false)
  const { postIcon } = useHttpRequestEffect()
  const handleRemove = (file: FileItem) => {
    const index = fileList.value.indexOf(file)
    const newFileList = fileList.value.slice()
    newFileList.splice(index, 1)
    fileList.value = newFileList
  }
  const beforeUpload = (file: FileItem) => {
    fileList.value = [...fileList.value, file]
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
    if (!isJpgOrPng) {
      message.error('请上传图片格式文件!')
    }
    const isLt10M = file.size / 1024 / 1024 < 10
    if (!isLt10M) {
      message.error('图片大小不能超过10MB!')
    }
    return isJpgOrPng && isLt10M && false
  }
  // 上传按钮
  const handleUpload = async () => {
    if (!fileList.value[0]) return
    const formData = new FormData()
    // console.log(toRaw(fileList.value[0].originFileObj))
    formData.append('file', toRaw(fileList.value[0].originFileObj) as any)
    uploading.value = true
    postIcon(formData).then(() => {
      uploading.value = false
      fileList.value = []
      isNull.value = false
    })
  }

  return {
    fileList,
    uploading,
    handleRemove,
    beforeUpload,
    handleUpload
  }
}

// 选择图标的相关逻辑
const useIconListEffect = () => {
  const current = ref<number | undefined>(undefined)
  const chosImg = ref<IconList>({
    path: '',
    url: ''
  })
  const chooseImg = (img: IconList, index: number) => {
    current.value = index
    chosImg.value = img
  }
  return { current, chosImg, chooseImg }
}

// 网络请求相关逻辑
const useHttpRequestEffect = () => {
  const token: string = localStorage.getItem('token') as string
  const isNull = ref<boolean>(true)
  const postIcon = async (formData: any) => {
    const res: any = await upload('/admin/api/v1/recruitment/icons/upload', formData, token)
    console.log(res)
    if (res.status_code === 0) {
      message.success('添加成功')
      iconList.value.push(res.data)
    } else {
      message.error(res.data.info)
    }
  }
  const getIconListData = async () => {
    const res: any = await get('/admin/api/v1/recruitment/icon/list', token)
    console.log(res)
    if (res.status_code === 0) {
      if (res.data) {
        isNull.value = false
        iconList.value = res?.data
      } else {
        isNull.value = true
      }
    }
  }
  const deleteIcon = async (icon_name: string) => {
    const res: any = await detele(`/admin/api/v1/recruitment/icons/${icon_name}`, {}, token)
    console.log(res)
    if (res.status_code === 0) {
      message.success('删除图标成功')
    }
  }
  return { isNull, postIcon, getIconListData, deleteIcon }
}

export default defineComponent({
  emits: ['chosIcon'],
  components: {
    PlusOutlined
  },
  setup(props, { emit }) {
    const { isNull, getIconListData } = useHttpRequestEffect()
    const { fileList, uploading, handleRemove, beforeUpload, handleUpload } = useUploadEffect(isNull)
    const { current, chosImg, chooseImg } = useIconListEffect()
    const { visible, showDrawer, closeDrawer, chooseIcon, removeIcon } = useDrawerEffect(emit, chosImg, isNull)

    onUpdated(() => {
      if (visible.value && iconList.value.length < 1) {
        getIconListData()
      }
    })

    return {
      visible,
      showDrawer,
      closeDrawer,
      removeIcon,
      fileList,
      uploading,
      handleRemove,
      beforeUpload,
      handleUpload,
      isNull,
      iconList,
      current,
      chosImg,
      chooseImg,
      chooseIcon
    }
  }
})
</script>

<style lang="less" scoped>
.iconList {
  border-bottom: 1px solid #f4f4f4;
  margin-bottom: 5px;
  &__title {
    color: #333;
    margin-top: 30px;
    padding-top: 10px;
    font-weight: 600;
    text-align: center;
    font-size: 18px;
    border-top: 1px solid #f4f4f4;
  }
  &__text {
    color: #999;
    text-align: center;
    font-size: 13px;
    padding-bottom: 5px;
    border-bottom: 1px solid #f4f4f4;
  }
  &__items {
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    img {
      width: 100%;
      height: 100%;
    }
    &__item {
      flex: 1;
      width: 33.3%;
      min-width: 33.3%; // 加入这两个后每个item的宽度就生效了
      max-width: 33.3%; // 加入这两个后每个item的宽度就生效了
      padding: 20px 10px;
    }
  }
}

.icon_border {
  border: 2px solid #e74c3c;
}
.ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
